/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.filters;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.gadglet.data.Gadget;
import com.gadglet.data.utils.PMF;
import com.gadglet.util.UrlUtils;


// Seems not to work when static resource exists ... TBD- check!
public class GadgetsProvider implements javax.servlet.Filter {
	public FilterConfig filterConfig;  
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpReq = null;
		String gadgetName = null;
		boolean continueRequest = true;
		
		// handle XML ignore all other requests ... 
		// As the system has a webserver in front the filter is invoked only for 
		// resources that doesn't exist (error 404) or JSP or /dir/ (no file name)
		// The Filer is invoked ONLY for xml requests that stored in the DataStore 
			 if (request instanceof HttpServletRequest) 
			 {
				 httpReq =  (HttpServletRequest) request;
				 
				//System.out.print("getServletPath = "+ httpReq.getServletPath());
				 
				 // check for xml request
				 if(UrlUtils.isXmlRequest(httpReq.getServletPath()))
				 {
					 gadgetName = UrlUtils.getGadgetName(httpReq.getServletPath());
					 			 
					 if(gadgetName != null)
					 {
						// load gadget xml and send back 
						// call the gadget xml
						   	PersistenceManager pm = PMF.get().getPersistenceManager();
						    Query query = pm.newQuery(Gadget.class);
						    query.setFilter("name == nameParam");
						    query.declareParameters("String nameParam");
						    
						    
						    try 
						    {
						    	query.setUnique(true); //solve the one gadget issue
						    	Gadget g  = (Gadget) query.execute(gadgetName);
						    	
								if (g!=null ) // ignore  g.isVisible() as the igoogle call doesn't include credentials
								{
									// XML file exists on server
									
									if(g.getGadgetFileName() != null && !g.getGadgetFileName().isEmpty())
										continueRequest = true;
									else
									{
										// XML in DataStore
										PrintWriter out = response.getWriter();
										response.setContentType("text/xml; charset=UTF-8");
										out.print(g.getXmlSource());
										continueRequest = false;
									}
										
								}
								
								
						 	}
						    catch (Exception e)
						    {
						    	e.printStackTrace();
						    }
						    finally 
						    {
						        query.closeAll();
						        pm.close();
						    }
					}
					 else
					 	continueRequest = false;
				 }
				 else
					 continueRequest = true;	 
	
				 
			 }
	
	// perform the request 
		if(continueRequest)
			chain.doFilter(request,response);
			
	}

	
	@Override
	public void init(FilterConfig conf) throws ServletException {
		this.filterConfig = conf;
		
	}
	
}
